package com.le.tester.book.concurrentchallenge.effScalingCache;

import java.util.Map;
import java.util.concurrent.*;

/**
 * createTime：2025-03-27 10:19
 * description：使用concurrentHashMap和Future来实现同步已经结果的及时通知，线程就不会阻塞
 */
public class Memoizerl3<A, V> implements Computable<A, V> {

    private final Map<A, Future<V>> cache = new ConcurrentHashMap<>();

    private final Computable<A, V> c;

    public Memoizerl3(Computable<A, V> c) {
        this.c = c;
    }

    @Override
    public V compute(final A arg) throws InterruptedException {
        Future<V> f = cache.get(arg);
        if (f == null) {
            Callable<V> eval = () -> c.compute(arg);
            FutureTask<V> ft = new FutureTask<>(eval);
            f = ft;
            cache.put(arg, ft);
            ft.run();
        }
        try {
            return f.get();
        } catch (ExecutionException e) {
            throw new RuntimeException(e.getCause());
        }
    }
}
